class User::ReportsController < ApplicationController

  before_filter :auth
  layout false
  def index
    @test_records =SurveyRecord.paginate :per_page => 20, :page=>params[:page],  
    :conditions => ["org_id = ? and deleted is null ", current_user.id],
    :order =>"created_at DESC"
    @test_record_num=SurveyRecord.find(:all, :conditions => ["org_id = ? and deleted is null", current_user.id]).size
    getfolders(1)
  end
  
  #========得到 最近三天 一周 一月的测试报告=================
  def get_reports_by_time
    timer=params[:timer]
     if timer == nil  
       timer=flash[:div_status]
     end
     if timer == "st"
       time_form=Time.now-3.day
     elsif timer == "yz"
       time_form=Time.now-7.day
      elsif timer == "yy"
         time_form=Time.now-1.month
    end
    
    @test_records =SurveyRecord.paginate :per_page => 20, :page=>params[:page],  
        :conditions => ["org_id = ? and deleted is null  and created_at > ? ", current_user.id , time_form],
        :order =>"created_at DESC"
    @test_record_num=SurveyRecord.find(:all , :conditions => ["org_id = ? and deleted is null  and created_at > ? ", 
    current_user.id , time_form]).size
    getfolders(1)
     if params[:page]==nil
       respond_to do |format|
         format.html { render :partial => "report_list"}
        end
     else
     @has_pages=true
      respond_to do |format|
        format.html { render :partial => "index"}
      end
    end
  end
  # 根据浏览器提交请求时的状态 返回 在del   mark  remove_marks 时用到
  def get_reports_by_flash
    flash.keep(:notice)
    timer=flash[:div_status]
      if timer == nil  
      timer="all"
     end
       if timer == "st"
         time_form=Time.now-3.day
      elsif timer == "yz"
       time_form=Time.now-7.day
      elsif timer == "yy"
         time_form=Time.now-1.month
      elsif timer =="all"
         time_form=Time.now-1.year
      end
    
      @test_records =SurveyRecord.paginate :per_page => 20, :page=>params[:page],  
          :conditions => ["org_id = ? and deleted is null  and created_at > ? ", current_user.id , time_form],
          :order =>"created_at DESC"
            #@test_record_num=SurveyRecord.find(:all, :conditions => ["org_id = ? and deleted is null", current_user.id]).size
      @test_record_num=SurveyRecord.find(:all , :conditions => ["org_id = ? and deleted is null  and created_at > ? ", 
      current_user.id , time_form]).size
      getfolders(1)
      respond_to do |format|
       format.html { render :partial => "report_list"  }
      end
      
  end
     #===========  end    ==============
    
    #未读的报告
  def get_new_reports
    @test_records =SurveyRecord.paginate :per_page => 20, :page=>params[:page],  
      :conditions => ["org_id = ? and deleted is null  and  been_read = false", current_user.id ],
      :order =>"created_at DESC"
     @test_record_num=SurveyRecord.find(:all , :conditions => ["org_id = ? and deleted is null  and  been_read = false", current_user.id ]).size
      getfolders(1)
   if params[:page]==nil
       respond_to do |format|
         format.html { render :partial => "report_list"}
        end
    else
    @has_pages=true
      respond_to do |format|
        format.html { render :partial => "index"}
      end
    end
  end
    
  #重要的报告
  
 def get_import_reports
    @test_records =SurveyRecord.paginate :per_page => 20, :page=>params[:page],  
      :conditions => ["org_id = ? and deleted is null  and  importance = '重要' ", current_user.id],
      :order =>"created_at DESC"
      @test_record_num=SurveyRecord.find(:all ,:conditions => ["org_id = ? and deleted is null  and  importance = '重要' ", current_user.id]).size
       getfolders(1)
     if params[:page]==nil
       respond_to do |format|
         format.html { render :partial => "report_list"}
        end
    else
      @has_pages=true
      respond_to do |format|
        format.html { render :partial => "index"}
      end
    end
  end
  
  def imp_marks
    arrs=params[:arr].split(",")
    arrs.each do |arr|
       if arr.length > 0
        report=SurveyRecord.find(arr)
        report.importance = "重要"
        report.save #update(d,f_id.to_i)
       end
     end
    flash[:notice]="标记已完成"
    flash[:div_status]=params[:status]
     if params[:status]=="new"
       get_new_reports
     elsif params[:status]=="imp"
       get_import_reports
     else
       get_reports_by_flash 
     end
    #respond_to do |format|
      #format.html { render :text => "<font color='red'>标记已完成.</font>"}
    #end
  end
    
  def remove_marks
    arrs=params[:arr].split(",")
    arrs.each do |arr|
      if arr.length > 0
        report=SurveyRecord.find(arr)
        report.importance = "普通"
        report.save #update(d,f_id.to_i)
      end
    end
    flash[:notice]="已取消标记"
    flash[:div_status]=params[:status]
     if params[:status]=="new"
       get_new_reports
     elsif params[:status]=="imp"
       get_import_reports
     else
       get_reports_by_flash 
     end
    #respond_to do |format|
     #format.html { render :text => "<font color='red'>取消标记完成,点此刷新页面后显示结果</font>"}
    #end
  end
  #创建新的 文件夹 
  def create_folder
     foldername=params[:name]
     if foldername.length > 0
        folder= Folder.new()
        folder.name=foldername
        folder.user_id=session[CURRENT_USER_ID]
        folder.save
      end
      getfolders(1)
     respond_to do |format|
         format.html { render :partial => "folders"}
     end
  end
   
   def getfolders(page)
      @all_folders=Folder.paginate :per_page => 20, :page=>page,
      :conditions=>" user_id = #{session[CURRENT_USER_ID].to_s}",
      :order =>"created_at DESC"
   end
   
   def get_npage_folder
     page_num=params[:page_num]
     getfolders(page_num)
    respond_to do |format|
        format.html { render :partial => "folders"}
     end
   end
    #显示 某一 目录下的所有报告
  def get_reports_by_folder
    @test_records =SurveyRecord.paginate :per_page => 20, :page=>params[:page],  
        :conditions => ["org_id = ? and deleted is null  and  folder_id = ? ", current_user.id , params[:id]],
        :order =>"created_at DESC"
        
         getfolders(1)
          #@test_record_num=SurveyRecord.find(:all, :conditions => ["org_id = ? and deleted is null", current_user.id]).size
     if params[:page]==nil
       respond_to do |format|
         format.html { render :partial => "report_list"}
        end
    else
      respond_to do |format|
        format.html { render :partial => "index"}
      end
    end
  end
    
  def  change_folder
    arrs=params[:arr].split(",")
    f_id=params[:f_id]

    if f_id
      arrs.each do |arr|
         if arr.length > 0
            report=SurveyRecord.find(arr)
            report.folder_id=f_id
            report.save #update(d,f_id.to_i)
         end
      end
      flash[:notice]="已移动到指定文件夹"
    else
      flash[:notice]= "没有选择文件夹"
    end

    flash[:div_status]=params[:status]
    get_reports_by_flash
    #  respond_to do |format|
     #   format.html{ render :text=>"<font color='red'>已移动到指定文件夹，请转到相应文件夹查看！</font>"}
     # end
  end
    
    
  def rename_folder
    new_name=params[:name]
    folder=Folder.find(params[:folder_id])
    folder.name=new_name
    folder.save
    getfolders(1)
    respond_to do |format|
      format.html {  render :partial=>"folders" }
    end
  end
   #删除文件夹
   def del_folder
     folder=Folder.find(params[:f_id])
     records=SurveyRecord.find(:all ,:conditions=>[" folder_id = ?" , params[:f_id].to_s])
     begin
       records.each do |r|
          r.folder_id=nil
          r.save 
       end
       folder.destroy
       getfolders(1)
      respond_to do |format|
        format.html { render :partial=>"folders"}
      end
    rescue 
      getfolders(1)
           puts " mei you shan chu"
      respond_to do |format|
        format.html { render :partial=>"folders"}
      end
    end
   end
  
  def delete_records
    arrs=params[:arr].split(",")
    arrs.each do |arr|
      if arr.length > 0
        record=SurveyRecord.find(arr)
        record.fake_delete  # 假删除
     end
   end
    flash[:notice]="所选记录已删除"
    flash[:div_status]=params[:status]
     if params[:status]=="new"
       get_new_reports
     elsif params[:status]=="imp"
       get_import_reports
     else
       get_reports_by_flash 
     end
   #  respond_to do |format|
   #     format.html { render :text=>"<a href='/user/reports/index'><font color='red'>已删除，请点此刷新页面 继续</font></a>"}
   # end
  end
  # 咨询师编辑意见
  def record_zxs_yj
      @test_record = SurveyRecord.find(params[:record_id])
      @test_record.zxs_yj = params[:test_record][:zxs_yj]
      @test_zxs_yj=@test_record.zxs_yj
      @test_record.save
      respond_to do |format|
       format.html { render :partial=>"zxs_yj"}
      end
  end
  
   
  def show_report
    @test_record = SurveyRecord.find(params[:id])
     @test_record.been_read=true
    @test_record.save
    @test=@test_record.survey

    #@report_json = report_json
    #如果是独立的量表，就使用单独的报告生成策略
    rg_method=@test_record.survey.rg_method
    
    if rg_method && rg_method.length !=0
    #if @test_record.survey.rg_method
      generate_report(@test_record.survey.rg_method)
    else
      do_report
      render :layout => false
    end
  end
  
  def admin_checkreport
     id=params[:id]
     redirect_to("/user/reports/show_report/#{id}?r=false")
  end
  
  
  def print_report
    @test_record = SurveyRecord.find(params[:id])
    if params[:r] = nil  #不是管理员查看则设置已读标记
      @test_record.been_read=true
      @test_record.save
    end
    @test=@test_record.survey
    #如果是独立的量表，就使用单独的报告生成策略
    rg_method=@test_record.survey.rg_method

    if rg_method && rg_method.length !=0
    #if @test_record.survey.rg_method
      generate_report(@test_record.survey.rg_method)
    else
      do_report
      render :layout => false
    end
  end
    
  def do_report
      #@test_record = SurveyRecord.find(params[:id])
      #统计分数
      @total = OriginalResult.sum(:value, :conditions => ["test_record_id = ?", @test_record.id])
      @avg = OriginalResult.average(:value, :conditions => ["test_record_id = ?", @test_record.id])

      @original_results = OriginalResult.find_all_by_test_record_id(@test_record.id)

      @part_results = OriginalResult.find_by_sql(
        [ "select part_id, sum(value) total, avg(value) avg from original_results
            where test_record_id = ? group by part_id", @test_record.id
        ]
      )

      @dimen_results = OriginalResult.find_by_sql(
        [ "select dimen_id, sum(value) total, avg(value) avg from
            (select question_id, value from original_results where test_record_id = ?) t1,
            (select * from dimens_questions) t2
           where t1.question_id = t2.question_id group by dimen_id",
          @test_record.id
        ]
      )

      @norms = Norm.cross_table(@test_record.survey_id.to_s)
      @test = @test_record.survey
      # 查出咨询师 意见
      @test_zxs_yj=@test_record.zxs_yj

  end
  
  #生成 dimen  fusioncharts xml
  def report_xml
     sql="select dimen_id, sum(value) total, avg(value) avg from
                (select question_id, value from original_results where test_record_id = #{params[:id]}) t1,
                (select * from dimens_questions) t2
               where t1.question_id = t2.question_id group by dimen_id"
       @dimen_results = OriginalResult.find_by_sql(sql)
       # puts sql
       headers["Content-Type"] = "text/xml; charset=utf-8"  # xml content with charset=uttf-8 
       render :layout => false
  end

  def report_json
    sql="select dimen_id, sum(value) total, avg(value) avg from
          (select question_id, value from original_results where test_record_id = #{@test_record.id}) t1,
          (select * from dimens_questions) t2
         where t1.question_id = t2.question_id group by dimen_id"
    @dimen_results = OriginalResult.find_by_sql(sql)

    json = "["
    for item in @dimen_results
      dimen = Dimen.find(item.dimen.id)
      if dimen.formula and dimen.formula.size > 0
        item_total = count_by_formula(item.total, dimen.formula)
        json += "['#{dimen.name}', #{item_total}], "
      else
        json += "['#{dimen.name}', #{item.total}], "
      end
    end

    json += "]"
    return json
    #render :text => json, :layout => false
  end

  #  分量表图表 xml 
  def part_report_xml
   sql="select part_id, sum(value) total, avg(value) avg from original_results
          where test_record_id = #{params[:id]} group by part_id"
   @part_results = OriginalResult.find_by_sql(sql)

    headers["Content-Type"] = "text/xml; charset=utf-8"  # xml content with charset=uttf-8
    render :layout => false
  end
  
  def ept_report_xml
      sql="select dimen_id, sum(value) total, avg(value) avg from
                (select question_id, value from original_results where test_record_id = #{params[:id]}) t1,
                (select * from dimens_questions) t2
               where t1.question_id = t2.question_id group by dimen_id"
      dimen_results = OriginalResult.find_by_sql(sql)
      test_record=SurveyRecord.find(params[:id])
      gender=test_record.gender
      @ept_drs=[]
     dimen_results.each do |dimen_r|
         item=[]
         if  dimen_r.total.to_i > 20
             dimen_r.total= 20
         end
         sql1="select * from ept_trans where original_mark = #{dimen_r.total}"
         t_result=EptTran.find_by_sql(sql1)
         if gender=="男"
             columnname=Dimen.find(dimen_r.dimen_id).name+"1".to_s
             dimen_r.total = t_result[0].send(columnname)
             item << dimen_r.dimen_id
             item << dimen_r.total
         else
            columnname=Dimen.find(dimen_r.dimen_id).name+"0".to_s
            dimen_r.total = t_result[0].send(columnname)
             item << dimen_r.dimen_id
             item << dimen_r.total
         end
         @ept_drs << item
       end
       headers["Content-Type"] = "text/xml; charset=utf-8"  # xml content with charset=uttf-8 
       render  :layout => false
  end
  

  def original_marks
    @test_record =SurveyRecord.find(params[:id])
    @test = @test_record.survey
    @parts=@test.parts
  
    @original_results=[]
    if @parts.size >=1
      @parts.each do |part|
      sql="select * from original_results where test_record_id= "+@test_record.id.to_s+" and part_id=  "+part.id.to_s
      @parts_results = OriginalResult.find_by_sql(sql)
      @original_results << @parts_results
      end
    else
      sql="select * from original_results where test_record_id= "+@test_record.id.to_s
      #puts sql
      @original_results=OriginalResult.find_by_sql(sql)
    end
    #@norms = Norm.cross_table(@test_record.test_id.to_s)
    render :layout => false
  end
  
  #每一个题目 以及所有选项 ，所属分量表 因子..
  def original_question
  begin
     question_id=params[:id]
     quest_body=Question.find(question_id)
     all_choices=Choice.find(:all,:conditions=>[" question_id = ?" ,question_id])
     str=" 题目： "+quest_body.description+" <br/>"
     str +="选项：<br />"
     i=0
     all_choices.each do |c|
       str +="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "+(i+65).chr+" .&nbsp;&nbsp;&nbsp;"
       str +=c.content+"  <br />"  
       i +=1
     end 
     part=quest_body.part
     dimens=quest_body.dimens
     if part
      str +="所属分量表：&nbsp;&nbsp;"
      str +=part.name+"  <br/>"
     end
     if dimens
       str+="所属因子： "
       dimens.each do |d|
       str +="&nbsp;&nbsp;&nbsp;&nbsp;"+d.name+" &nbsp;&nbsp;&nbsp;&nbsp;"
       end 
     end
     render :layout => false ,:text=>str
  rescue Exception => exc
    str=""
    logger.error("#{exc.message}")
    render :layout => false ,:text=>str
  end
  end

  def destroy
    @test_record = SurveyRecord.find(params[:id])
    @test_record.fake_delete
    redirect_to :action => "index"
  end
  
  
  def search
     keyword=params[:keyword]
     flash[:keyword]=keyword
     date1=params[:date][:date1]
     flash[:date1]=date1
     date2=params[:date][:date2]
     page_num=params[:page_num]
     #user_id=params[:user_id]
    flash[:date2]=date2
    if date1==""
      date1=DateTime.civil(2009,1,1,00,00,00).to_json
    end
    if date2 ==""
      date2=DateTime.civil(2100,1,1,00,00,00).to_json
    end
    if page_num == nil
      page_num=1
    end
    @status="search"
     sql="select * from survey_records  where (testname like '%"+keyword+"%' or username like '%"+keyword+"%') and  created_at > '"+date1.to_datetime.to_s+"'  and  created_at < '"+date2.to_datetime.to_s+"'  and  org_id = "+session[CURRENT_USER_ID].to_s+"    order by created_at DESC"
     @test_records=SurveyRecord.paginate_by_sql(sql,{:per_page => 20, :page=>page_num})
     respond_to do |format|
         format.html { render :partial => "report_list"}
     end
  end
  def search_folder
     keyword=params[:keyword]
     flash[:keyword]=keyword
     date1=params[:date][:date1]
     flash[:date1]=date1
     date2=params[:date][:date2]
     page_num=params[:fpage_num]
     #user_id=params[:user_id]
    flash[:date2]=date2
    if date1==""
      date1=DateTime.civil(2009,1,1,00,00,00).to_json
    end
    if date2 ==""
      date2=DateTime.civil(2100,1,1,00,00,00).to_json
    end
    if page_num == nil
      page_num=1
    end
    @folder_status="folder"  
    sql="select * from folders where  name like '%#{keyword}%' and  created_at > '"+date1.to_datetime.to_s+"'  and  created_at < '"+date2.to_datetime.to_s+"'  and  user_id = "+session[CURRENT_USER_ID].to_s+" order by created_at DESC"
    @all_folders=Folder.paginate_by_sql(sql,{:per_page => 5, :page=>page_num})
     
     respond_to do |format|
         format.html { render :partial => "folders"}
     end  
  end


  def _report
    @norm_info = NormInfo.find(params[:id])
    render :layout => false
  end
  
   #---------------------独立量表--------------------
  def generate_report(generate_method)
    send(generate_method)
  end

  def mmpi
    @report = CustomSurveys::Mmpi.report(@test_record)
    @t_json = CustomSurveys::Mmpi.pre_t_json(@report)
    respond_to do |format|
      format.html { render :template => "user/reports/custom/mmpi", :layout => 'report'}
    end
  end

  def sixteen
    do_report
    @expls = CustomSurveys::Sixteen.expls(@dimen_results, @test_record.gender)
    render :template => "user/reports/custom/sixteen", :layout => 'report'
  end
  
  def ept
    do_report
    gender=@test_record.gender
    if gender== nil 
        gender="男"
    end
    @ept_avg=@avg
    @ept_total=0

     @dimen_results.each do |dimen_r|
       if  dimen_r.total.to_i > 20
           dimen_r.total= 20
       end
       sql="select * from ept_trans where original_mark = #{dimen_r.total}"
       t_result=EptTran.find_by_sql(sql)
       if gender=="男"
           columnname=Dimen.find(dimen_r.dimen_id).name+"1".to_s
           dimen_r.total = t_result[0].send(columnname)
           @ept_total +=dimen_r.total
       else
          columnname=Dimen.find(dimen_r.dimen_id).name+"0"
          dimen_r.total = t_result[0].send(columnname)
          @ept_total +=dimen_r.total
       end
     end
    render :template => "user/reports/custom/ept", :layout => false
  end
   
  def ruiwen
    do_report
    #获取 被测者 年龄
    age= @test_record.age
    if age==nil || age < 5
        age=5
    elsif age >=17.1
        age=20
    end
    get_ruiwen_marks(age,@total)
    
    render   :template => "user/reports/custom/ruiwen" , :layout => false
   end
   
   def get_ruiwen_marks(age,tatol)
     data = YAML.load_file(RAILS_ROOT + "/db/yaml/ruiwen.yml")
     column_name="age"
     @index=6
     str=age.to_s
     str1=str.split(".")
       if str1.size >1
         column_name=column_name+str1[0]+str1[1]
       else
          column_name=column_name+str
       end
     #puts  data[send(#{column_name})]
     data_arr=data[:"#{column_name}"]
    for i in 1...data_arr.size
       if tatol >= data_arr[i]
           @index=i
           break
       end
    end
  #   puts @index.to_s+"-=-=-=-=-=-=-=-=-="+data_arr[@index].to_s
    @total_mark=data[:or_marks][@index];
   #p @total_mark
  end
  
  def  ruiwen_xml
   headers["Content-Type"] = "text/xml; charset=utf-8"  # xml content with charset=uttf-8 
    render   :template => "user/reports/custom/ruiwen_xml" , :layout => false
  end
  #-----------------------------------------------
  
end
